package com.hunantv.mglive.ui.act;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.VODModel;
import com.hunantv.mglive.data.discovery.WatchMMData;
import com.hunantv.mglive.ui.discovery.MaxSeekBar;
import com.hunantv.mglive.ui.live.StarDetailActivity;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.HttpUtils;
import com.hunantv.mglive.utils.MGTVUtil;
import com.hunantv.mglive.utils.ReportUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.widget.media.IjkVideoView;
import com.hunantv.mglive.widget.media.VideoController;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by June Kwok on 2016-1-27.
 */
public class PkVideoCard extends FrameLayout implements HttpUtils.callBack, View.OnClickListener {
    private HttpUtils mHttp;
    private WatchMMData mData;
    private String mVideoPath = "";
    private LayoutInflater mInflater;
    private CardViewHolder mNormalCard;
    boolean isVideoStared = false, isAnimaStared = false;
    int progress;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    start();
                    break;
                case 1:
                    stop();
                    break;
                default:
                    break;
            }
        }
    };

    public void startVideo() {
        isVideoStared = true;
        if (StringUtil.isNullorEmpty(mVideoPath)) {
            return;
        }
        if (null != mHandler) {
            mHandler.sendEmptyMessageDelayed(0, 200);
        }
    }

    public void stopVideo() {
        isVideoStared = false;
        if (null != mHandler) {
            mHandler.sendEmptyMessageDelayed(1, 10);
        }
    }

    public void start() {
        if (null == mNormalCard || null == mNormalCard.mVideoView) {
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("auid", mData.getUid());
        params.put("mid", mData.getVideo());
        params.put("ap", "1");
        mNormalCard.mVideoView.setVideoPath(mVideoPath, params, IjkVideoView.VideoType.vod);
        mNormalCard.mVideoView.requestFocus();
        mNormalCard.mVideoView.start();
    }

    public void continuePlay() {
        if (null == mNormalCard || null == mNormalCard.mVideoView || mNormalCard.mVideoView.isPlaying() || StringUtil.isNullorEmpty(mVideoPath)) {
            return;
        }
        mNormalCard.mVideoView.start();
    }

    public void pause() {
        if (null != mNormalCard.mVideoView && mNormalCard.mVideoView.isPlaying()) {
            mNormalCard.mVideoView.pause();
        }
    }

    public void stop() {
        if (null == mNormalCard || null != mNormalCard.mVideoView) {
            mNormalCard.mVideoView.stopPlayback();
        }
    }

    public PkVideoCard(Context context, WatchMMData mData) {
        super(context);
        this.mHttp = new HttpUtils(context, this);
        this.mData = mData;
        this.mInflater = LayoutInflater.from(context);
        initView();
        loadData();
    }

    private void initView() {
        View view = mInflater.inflate(R.layout.card_content, this, false);
        LayoutParams mViewLP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mViewLP.gravity = Gravity.CENTER;
        addView(view, mViewLP);
        initViewHolder(view);
    }

    private void initViewHolder(View view) {
        mNormalCard = new CardViewHolder();
        mNormalCard.mVideoParent = (FrameLayout) view.findViewById(R.id.nomal_video_parent);
        mNormalCard.mVideoView = (IjkVideoView) view.findViewById(R.id.nomal_video_part);
        mNormalCard.mVideoCover = (ImageView) view.findViewById(R.id.nomal_video_cover);
        RelativeLayout.LayoutParams mVideoLP = (RelativeLayout.LayoutParams) mNormalCard.mVideoParent.getLayoutParams();
        mVideoLP.height = Constant.toPixByHeight(525);
        mNormalCard.mVideoParent.setLayoutParams(mVideoLP);
        mNormalCard.mHeadIcon = (ImageView) view.findViewById(R.id.nomal_user_head);
        mNormalCard.mUserName = (TextView) view.findViewById(R.id.nomal_user_name);
        mNormalCard.mBtnShare = (ImageView) view.findViewById(R.id.normal_btn_share);
        mNormalCard.mBtnChat = (ImageView) view.findViewById(R.id.normal_btn_chat);
        mNormalCard.mBtnFlow = (ImageView) view.findViewById(R.id.normal_btn_flow);
        mNormalCard.mBtnFlowTxt = (TextView) view.findViewById(R.id.normal_btn_flow_txt);
        mNormalCard.mSeekBar = new MaxSeekBar(getContext());
        LayoutParams mSeekBarLP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mSeekBarLP.gravity = Gravity.CENTER;
        mNormalCard.mVideoParent.addView(mNormalCard.mSeekBar, mSeekBarLP);
        mNormalCard.mController = new VideoController(getContext());
        mNormalCard.mVideoView.setController(mNormalCard.mController);
        mNormalCard.mVideoView.setViewParams(mVideoLP.width, mVideoLP.height);
        mNormalCard.mController.initControllerView(mNormalCard.mSeekBar.mSeekHolder.mBtnPause, mNormalCard.mSeekBar.mSeekHolder.mSeekbar, null, null);
        mNormalCard.mController.show();
        mNormalCard.mVideoView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(IMediaPlayer mp) {
                startVideoAnima(mNormalCard.mVideoCover);
            }
        });
        mNormalCard.mVideoView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer mp) {
                mNormalCard.mVideoView.start();
            }
        });
        mNormalCard.mBtnFlow.setSelected(mData.isFollowed());
        mNormalCard.mBtnFlowTxt.setText(mData.isFollowed() ? "已粉(" + mData.getFansCount() + ")" : "粉TA");

        mNormalCard.mBtnChat.setOnClickListener(this);
        mNormalCard.mBtnFlow.setOnClickListener(this);
        mNormalCard.mBtnFlowTxt.setOnClickListener(this);
        mNormalCard.mBtnShare.setOnClickListener(this);
        mNormalCard.mHeadIcon.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.nomal_user_head || v.getId() == R.id.normal_btn_chat){
            if (null != mData && !StringUtil.isNullorEmpty(mData.getUid())) {
                Intent intent = new Intent(getContext(), StarDetailActivity.class);
                intent.putExtra(StarDetailActivity.KEY_STAR_ID, mData.getUid());
                intent.putExtra(StarDetailActivity.KEY_DYNAMIC_VIDEO_ID, mData.getVideo());
                getContext().startActivity(intent);
            }
        }else if(v.getId() == R.id.normal_btn_share){
        }else if(v.getId() == R.id.normal_btn_flow || v.getId() == R.id.normal_btn_flow_txt){
            if (null != mData) {
                if (!mData.isFollowed()) {
                    addFlow(mData.getUid());
                } else {
                    removeFlow(mData.getUid());
                }
                mData.setIsFollowed(!mData.isFollowed());
                mNormalCard.mBtnFlow.setSelected(mData.isFollowed());
                mNormalCard.mBtnFlowTxt.setText(mData.isFollowed() ? "已粉(" + mData.getFansCount() + ")" : "粉TA");
            }
        }
    }

    /**
     * 隐藏封面
     *
     * @param v
     */
    public void startVideoAnima(View v) {
        if (isAnimaStared) {
            return;
        }
        Animation mAlpaAnima = new AlphaAnimation(1.0f, 0.0f);
        mAlpaAnima.setDuration(300);
        mAlpaAnima.setFillEnabled(true);
        mAlpaAnima.setFillAfter(true);
        v.startAnimation(mAlpaAnima);
        isAnimaStared = true;
    }

    private void loadData() {
        if (null != mData && null != mNormalCard) {
            if (!StringUtil.isNullorEmpty(mData.getUid())) {
                getIsFlowed(mData.getUid());
            }
            if (!StringUtil.isNullorEmpty(mData.getVideo())) {
                requestVideoUrl(mData.getVideo());
            }
            Glide.with(getContext()).load(mData.getCover()).centerCrop().into(mNormalCard.mVideoCover);
            mNormalCard.mUserName.setText(mData.getNickName());
            Glide.with(getContext()).load(mData.getPhoto())
                    .placeholder(R.drawable.default_icon_preload).error(R.drawable.default_icon)
                    .transform(new GlideRoundTransform(getContext(), R.dimen.height_55dp)).into(mNormalCard.mHeadIcon);


        }
    }

    /**
     * 是否粉
     */
    private void getIsFlowed(String id) {
        if (MaxApplication.getInstance().isLogin()) {
            Map<String, String> param = new FormEncodingBuilderEx().add("uid", MaxApplication.getInstance().getUid()).add("token", MaxApplication.getInstance().getToken()).add("artistId", id).build();
            post(BuildConfig.URL_GET_IS_FOLLOWED, param);
        } else {
            //jumpToLogin("登录以后才可以粉TA哦~");
        }
    }

    /**
     * 去粉
     */
    private boolean removeFlow(String id) {
        boolean bol = false;
        if (MaxApplication.getInstance().isLogin()) {
            Map<String, String> param = new FormEncodingBuilderEx().add("uid", MaxApplication.getInstance().getUid()).add("token", MaxApplication.getInstance().getToken()).add("followid", id).build();
            post(BuildConfig.URL_REMOVE_FOLLOW, param);
            bol = true;
        } else {
            jumpToLogin("登录以后才可以粉取消哦~");
            bol = false;
        }
        return bol;
    }

    /**
     * 加粉
     */
    private boolean addFlow(String id) {
        boolean bol = false;
        if (MaxApplication.getInstance().isLogin()) {
            Map<String, String> param = new FormEncodingBuilderEx().add("uid", MaxApplication.getInstance().getUid()).add("token", MaxApplication.getInstance().getToken()).add("followid", id).build();
            post(BuildConfig.URL_ADD_FOLLOW, param);
            bol = true;
        } else {
            jumpToLogin("登录以后才可以粉TA哦~");
            bol = false;
        }
        return bol;
    }

    /**
     * Post请求视频地址
     *
     * @param key 视频文件名
     */
    private void requestVideoUrl(String key) {
        Map<String, String> param = new FormEncodingBuilderEx()
                .add(Constant.KEY_MEDIAID, key)
                .add(Constant.KEY_RATE, "SD")
                .add(Constant.KEY_TYPE, "key")
                .add(Constant.KEY_USER_ID, MaxApplication.getInstance().getUid())
                .add(Constant.KEY_USER_ID, MaxApplication.getInstance().getToken())
                .build();
        post(BuildConfig.URL_GET_VIDEO_URL, param);
    }

    /**
     * 跳转到登陆页面
     */
    public void jumpToLogin(String title) {
        MGTVUtil.getInstance().login(MaxApplication.getAppContext());
    }

    /**
     * 跳转到登陆页面
     */
    public void jumpToLogin(Intent intent) {
        MGTVUtil.getInstance().login(MaxApplication.getAppContext());
    }


    @Override
    public boolean get(String url, Map<String, String> param) {
        return mHttp.get(url, param);
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return mHttp.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {

    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        return null;
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url)) {
            try {
                //把code转成2开头
                String responseCode = resultModel.getResponseCode();
                if(!StringUtil.isNullorEmpty(responseCode)){
                    String subFirst = responseCode.substring(0,1);
                    responseCode = responseCode.replace(subFirst,"2");
                }
                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", responseCode, false);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
        Log.i("JUNE", "url=" + url);
        Log.i("JUNE", "data=" + resultModel.getData());
        if (url.contains(BuildConfig.URL_GET_VIDEO_URL)) {
            VODModel vod = JSON.parseObject(resultModel.getData(), VODModel.class);
            if(vod != null){
                if(vod.isMgtvType()){
                    getVodUrl(vod.getPlayUrl());
                }else{
                    playVod(vod.getPlayUrl());
                }
            }
        } else if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url))
        {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                playVod(jsonData.getString("info"));


                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", "", true);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if (url.contains(BuildConfig.URL_GET_IS_FOLLOWED)) {
            JSONObject jsonData = new JSONObject(resultModel.getData());
            mData.setIsFollowed(jsonData.getBoolean("isFollowed"));
            mNormalCard.mBtnFlow.setSelected(mData.isFollowed());
            mNormalCard.mBtnFlowTxt.setText(mData.isFollowed() ? "已粉(" + mData.getFansCount() + ")" : "粉TA");
        }
    }

    //点播类型为MGTV时缓存请求URl
    private String mVodRequestUrl;

    private void getVodUrl(String url){
        mVodRequestUrl = url;
        if(!StringUtil.isNullorEmpty(mVodRequestUrl)){
            get(url,null);
        }
    }

    private void playVod(String url){
        this.mVideoPath = url;
        if (isVideoStared) {
            startVideo();
        }
    }

    /**
     * 释放资源,解除耦合,减少内存的占用.
     */
    public void onDestory() {
        try {
            stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            try {
                Glide.with(getContext()).onLowMemory();
            } catch (Exception e) {

            }
            try {
                mHttp.cancelAll();
                mHttp.setCallBack(null);
            } catch (Exception e) {

            }
            mHttp = null;
            mData = null;
            mVideoPath = null;
            mInflater = null;
            try {
                Glide.clear(mNormalCard.mVideoCover);
            } catch (Exception e) {

            }
            try {
                Glide.clear(mNormalCard.mHeadIcon);
            } catch (Exception e) {

            }
            mHandler = null;
            try {
                if (null != mNormalCard) {
                    mNormalCard.onDestory();
                    mNormalCard = null;
                }
            } catch (Exception e) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class CardViewHolder {
        VideoController mController;
        FrameLayout mVideoParent;
        IjkVideoView mVideoView;
        ImageView mVideoCover;
        ImageView mHeadIcon;
        TextView mUserName;
        ImageView mBtnShare;
        ImageView mBtnChat;
        ImageView mBtnFlow;
        TextView mBtnFlowTxt;
        MaxSeekBar mSeekBar;

        private void onDestory() {
            mController = null;
            mVideoParent = null;
            mVideoView = null;
            mVideoCover = null;
            mHeadIcon = null;
            mUserName = null;
            mBtnShare = null;
            mBtnChat = null;
            mBtnFlow = null;
            mBtnFlowTxt = null;
            mSeekBar = null;
        }
    }
}
